package com.yygo.webapp.controller;

import com.yygo.model.Bank;
import com.yygo.model.LabelValue;
import com.yygo.model.LoanProduct;
import com.yygo.model.vo.BondCompanyVO;
import com.yygo.service.BankManager;
import com.yygo.service.BondManager;
import com.yygo.service.LoanProductManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Controller
@RequestMapping("/loanProductform*")
public class LoanProductFormController extends BaseFormController {
    private LoanProductManager loanProductManager = null;

    @Autowired
    private BondManager bondManager;

    @Autowired
    private BankManager bankManager;

    @Autowired
    public void setLoanProductManager(LoanProductManager loanProductManager) {
        this.loanProductManager = loanProductManager;
    }

    public LoanProductFormController() {
        setCancelView("redirect:loanProducts");
        setSuccessView("redirect:loanProducts");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    protected LoanProduct showForm(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        LoanProduct loanProduct = null;
        if (!StringUtils.isBlank(id)) {
          loanProduct = loanProductManager.loadLoanProduct(new Long(id));
        } else {
            loanProduct = new LoanProduct();
            String bankId = request.getParameter("bankId");
            if (!StringUtils.isBlank(bankId)) {
                Bank bank = bankManager.get(new Long(bankId));
                loanProduct.setBank(bank);
            } else {
                throw new IllegalAccessException("illegal access: bank id is empty.");
            }
        }

        return loanProduct;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(LoanProduct loanProduct, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {
        if (loanProduct.getBank().getId() == null) {
            throw new IllegalAccessException("illegal access: bank id is empty.");
        } else {
            Bank bank = bankManager.get(loanProduct.getBank().getId());
            loanProduct.setBank(bank);
        }

        String from = request.getParameter("from");
        if (request.getParameter("cancel") != null) {
            if (from.equals("bank"))
                return "redirect:/bankform?id=" + loanProduct.getBank().getId();
            else
                return "redirect:/loanProducts";
        }

        if (validator != null) { // validator is null during testing
            validator.validate(loanProduct, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "loanProductform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (loanProduct.getId() == null);
        String success = "redirect:/bankform?id=" + loanProduct.getBank().getId();
        if (from.equals("list"))
            success = "redirect:/loanProducts";

        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            loanProduct.setDeleted(true);
            loanProductManager.save(loanProduct);
            saveMessage(request, getText("loanProduct.deleted", locale));
        } else {
            loanProductManager.saveLoanProduct(loanProduct);

            String key = (isNew) ? "loanProduct.added" : "loanProduct.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew)
                success = "loanProductform";
        }

        return success;
    }

  @ModelAttribute("availableBondCompany")
  protected List<BondCompanyVO> getAvailableBondCompany() {
    //List<LabelValue> list = new ArrayList<LabelValue>();
    List<BondCompanyVO> companies = bondManager.loadAllChildTree();

    return companies;
  }

    @ModelAttribute("availableMaterialNames")
    protected List<LabelValue> getAvailableMaterialNames() {
        return getList("MATERIAL");
    }
}
